<template>
  <view>
    <view class="login-box">
      <uni-icons type="contact-filled" size="100" color="#afafaf"></uni-icons>
      <button type="primary" @click="gotoLogin" open-type="getUserInfo" @getuserinfo="getuserinfo">一键登录</button>
      <text>登录后享受更多权益</text>
    </view>

  </view>
</template>

<script>
  import {
    mapState,
    mapMutations,
    mapGetters
  } from 'Vuex'
  export default {
    name: "my-login",
    computed: {
      ...mapState('m_user', ['token','redirectInfo']),
    },
    data() {
      return {

      };
    },
    methods: {
      ...mapMutations('m_user', ['updateUserinfo', 'updateToken','updateRedirectInfo']),
      gotoLogin() {},
      //用户授权后获取基本信息
      getuserinfo(e) {
        if (e.detail.errMsg === 'getUserInfo:fail auth deny') return uni.$showMsg('您取消了用户授权!')
        this.updateUserinfo(e.detail.userInfo)
        this.getToken(e.detail)
      },
      navigateBack(){
        if(this.redirectInfo.type==='switchTab'){
          uni.switchTab({
            url:this.redirectInfo.from,
          complete:()=> {
            this.updateRedirectInfo(null)
          }
          })
        }
      },
      async getToken(info) {
        const {
          errMsg,
          code
        } = await uni.login()
        if (errMsg !== 'login:ok') return uni.$showMsg('登录失败!')
        const queryLogin = {
          code: code,
          encryptedData: info.encryptedData,
          iv: info.iv,
          rawData: info.rawData,
          signature: info.signature
        }
        const {
          data: res
        } = await uni.$http.post('/api/public/v1/users/wxlogin', queryLogin)
        if (res.meta.status != 400 && res.meta.status != 200) return uni.$showMsg('登录失败!')
        uni.$showMsg('登录成功!')
        this.updateToken( '我是token')
        // 导航回去
        
        if(this.redirectInfo){
          this.navigateBack()
        }
      }
    }
  }
</script>

<style lang="scss">
  .login-box {
    display: flex;
    height: 750rpx;
    width: 100%;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    background-color: #f8f8f8;

    button {
      border-radius: 100px;
      width: 90%;
      margin: 15px 0px;
      background-color: #c00000;
    }

    text {
      color: gray;
    }
  }
</style>